package Concurrency2.Chapter02_InnerLockPrinciple.scene;

import java.util.ArrayList;
import java.util.concurrent.CountDownLatch;

import static utils.MUtils.*;

/**
 * Instruction：展示线程安全问题
 * 测试内容: 多线程对共享变量做累加1million次, 测试线程安全问题
 * Author：@author MaLi
 */
public class T01_Accumulation {

    private static /*volatile*/ int sharedNum = 0;  // 多线程共享数据
    private static int TIMES = 10000;               // 每个线程累加次数
    private static int THREADS_QUANTITY = 10;       // 线程个数
    private static ArrayList<Thread> threads = new ArrayList<>(THREADS_QUANTITY);   //保存线程

    // 用于同步: THREADS_QUANTITY个线程全部执行完成, 放行主线程
    private static CountDownLatch countDownLatch = new CountDownLatch(10);

    public static void main(String[] args) {
        //创建线程
        for (int j = 0; j < THREADS_QUANTITY; j++) {
            Thread thread = new Thread(() -> {
                // 线程内容
                for (int i = 0; i < TIMES; i++) {
                    //sharedNum++;
                    sharedNum = sharedNum + 1;
                }
                print("ThreadName" + Thread.currentThread().getName() + " 执行完毕");
                countDownLatch.countDown();
            });
            threads.add(thread);
        }
        //启动线程
        for (Thread thread : threads) {
            thread.start();
        }
        //主线程等待全部线程执行完毕, 输出计数结果
        try {

            countDownLatch.await();
            System.out.println("sharedNum :" + sharedNum);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }
}
